<?php

$numResultsPerPage = 50;

$pageNum = (int) get('pageNum');
if($pageNum == 0) $pageNum = 1;

if(Antz_IntelliForm::submitted('IUsers_AdminSearch', false)){
    $pageNum = 1;
}


$groups = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_groups ORDER BY title ASC");

if(!isset($USER->IUsers_AdminSearchParams)) $USER->IUsers_AdminSearchParams = array(
	'username' => '%',
	'last_name' => '%',
	'first_name' => '%',
	'business_name' => '%',
	'group' => '0'
);

$sParams = $USER->IUsers_AdminSearchParams;

$sel = $DB->select();
$sel->order('username', 'ASC');

$username = preg_replace('/[^0-9a-zA-Z%]/', '', post('username', ''));
$busName = strtolower(post('business_name', ''));
$fName = strtolower(post('first_name', ''));
$lName = strtolower(post('last_name', ''));
$group = preg_replace('/[^a-zA-Z0-9_\-]/', '', post('group', '0'));

if(post('group') == $this->Lang('all_groups')){
	$sParams['group'] = '0';
	$group = '0';
}elseif($group != '0'){
	$sel->where('LOWER(groups.group_key)', $group);
	$sParams['group'] = $group;
}elseif($sParams['group'] != '0'){
	$sel->where('LOWER(groups.group_key)', $sParams['group']);
};
if($busName != ''){
    $sel->where('LOWER(iusers.business_name)', $busName, 'LIKE');
    $sParams['business_name'] = $busName;
}elseif($sParams['business_name'] != '%'){
    $sel->where('LOWER(iusers.business_name)', $sParams['business_name'], 'LIKE');
}else{
    $sParams['business_name'] = '%';
    $sel->where('LOWER(iusers.business_name)', '%', 'LIKE');
};
if($username != ''){
    $sel->where('LOWER(iusers.username)', $username, 'LIKE');
    $sParams['username'] = $username;
}elseif($sParams['username'] != '%'){
    $sel->where('LOWER(iusers.username)', $sParams['username'], 'LIKE');
}else{
    $sParams['username'] = '%';
    $sel->where('LOWER(iusers.username)', '%', 'LIKE');
};
if($fName != ''){
    $sel->where('LOWER(iusers.first_name)', $fName, 'LIKE');
    $sParams['first_name'] = $fName;
}elseif($sParams['first_name'] != '%'){
    $sel->where('LOWER(iusers.first_name)', $sParams['first_name'], 'LIKE');
}else{
    $sParams['first_name'] = '%';
    $sel->where('LOWER(iusers.first_name)', '%', 'LIKE');
};
if($lName != ''){
    $sel->where('LOWER(iusers.last_name)', $lName, 'LIKE');
    $sParams['last_name'] = $lName;
}elseif($sParams['last_name'] != ''){
    $sel->where('LOWER(iusers.last_name)', $sParams['last_name'], 'LIKE');
}else{
    $sParams['last_name'] = '%';
    $sel->where('LOWER(iusers.last_name)', '%', 'LIKE');
};


// get the search results
$sel->from($this->config['db_prefix'].'iusers iusers', '*');
if($sParams['group'] != '0'){
  $sel->join($this->config['db_prefix'].'iusers_to_groups groups', 'iusers.id = groups.user_id');
}

// count our results
$hookParams = array(
	'select_object' => $sel,
	'search_params' => &$sParams
);
$hookParams = Antz::Hookup('IUsers_AdminSearchProcess', $hookParams);
$sel = $hookParams['params']['select_object'];
$sParams = $hookParams['params']['search_params'];
unset($newSel);

$sel->what('COUNT(*)');
$sel->limit(500000, 0);
$numResults = $DB->fetchRow($sel);
$numResults = (int) $numResults['COUNT(*)'];


// fetch the resulting data
$sel->what('*');

// limit to page results
$sel->limit($numResultsPerPage, ($pageNum-1)*$numResultsPerPage);

$users = $DB->fetchAll($sel);


// pagination
$numPages = ceil($numResults/$numResultsPerPage);
$pagi = Antz::newObject('Antz_Pagination');
$url = $actionUrls['view'].'&amp;pageNum=:|pagenum|:';
$pagiLinks = $pagi->makeLinks($numPages, $pageNum, $url);


// display our search results
foreach($users as $k=>$v){
    $grps = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_to_groups WHERE user_id = '{$v['id']}'");
    $g = array();
    foreach($grps as $key=>$value){
        $g[] = $value['group_key'];
    };
    $users[$k]['groups'] = implode(',', $g);
    $users[$k]['email'] = $CRYPT->decrypt($v['email_crypt']);
};


// prepare our table for each user
$tables = array();

foreach($users as $k=>$uData){
	$tableKey = count($tables);
	$tables[$tableKey] = array(
    'heading' => $uData['business_name'], 
    'user_data' => $uData,
    'rows' => array()
  );

	// insert the data into the row
	$address = $uData['address']."\n";
	$address .= $DB->oneValue(cms_db_prefix().'iusers_cities', 'title', "id = '{$uData['city']}'")."\n";
	$address .= $DB->oneValue(cms_db_prefix().'iusers_countries', 'title', "id = '{$uData['country']}'");

	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('userid'), 
    'td' => $uData['id'],
    'name' => 'user_id'  
  );
	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('username'), 
    'td' => $uData['username'],
    'name' => 'username'
  );
	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('groups'), 
    'td' => $uData['groups'],
    'name' => 'groups'
  );
	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('name'), 
    'td' => $uData['first_name'].' '.$uData['last_name'],
    'name' => 'name'
  );
	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('email'), 
    'td' => $CRYPT->decrypt($uData['email_crypt']),
    'name' => 'email'
  );
	$tables[$tableKey]['rows'][] = array(
    'th' => $this->Lang('address'), 
    'td' => nl2br($address),
    'name' => 'address'
  );

}

// hand it out for other modules to add their data to the tables
$hookParams = array('tables' => $tables);
$newTable = Antz::Hookup('IUsers_AdminSearchDisplay', $hookParams);
$tables = $newTable['params']['tables'];
unset($newTable);


// create our search form
$groupOpts = array($this->Lang('all_groups') => $this->Lang('all_groups'));
foreach($groups as $k=>$v){
  $groupOpts[$v['keyname']] = $v['title'].' ['.$v['keyname'].']';
}

$formFields = array(
	array(
		'name' => 'username',
		'type' => 'text',
		'value' => $sParams['username'],
		'label' => $this->Lang('username')
	),
	array(
		'name' => 'business_name',
		'type' => 'text',
		'value' => $sParams['business_name'],
		'label' => $this->Lang('business_name')
	),
	array(
		'name' => 'first_name',
		'type' => 'text',
		'value' => $sParams['first_name'],
		'label' => $this->Lang('first_name')
	),
	array(
		'name' => 'last_name',
		'type' => 'text',
		'value' => $sParams['last_name'],
		'label' => $this->Lang('last_name')
	),
	array(
    'name' => 'group',
    'type' => 'select',
    'value' => $sParams['group'],
    'label' => $this->Lang('groups'),
    'options' => $groupOpts
  )
);

$hookParams = array(
    'form_fields' => $formFields, 
    'search_params' => $sParams
);
$hookParams = Antz::Hookup('IUsers_AdminSearchForm', $hookParams);
$formFields = $hookParams['params']['form_fields'];
$sParams = $hookParams['params']['search_params'];
unset($newFormFields);

$form = Antz::makeRapidForm($formFields, $this->Lang('search_params'), 'IUsers_AdminSearch');
$form->addSubmit($this->Lang('search'));
$form->setAction($actionUrls['view']);

$USER->IUsers_AdminSearchParams = $sParams;

/*
// build the search form
$form = Antz::newObject('Antz_Form', __FILE__);
$form->setAction($actionUrls['view']);
$block = $form->add('full');
$fs = $block->add('Search parameters');
$fs->addInput('text', 'v_username', $this->Lang('username_with_wildcard'), $USER->IUsers_AdminView->username);
$fs->addInput('text', 'v_busName', $this->Lang('business_name_with_wildcard'), $USER->IUsers_AdminView->busName);
$fs->addInput('text', 'v_fName', $this->Lang('first_name_with_wildcard'), $USER->IUsers_AdminView->fName);
$fs->addInput('text', 'v_lName', $this->Lang('last_name_with_wildcard'), $USER->IUsers_AdminView->lName);

$groupSel = $fs->addSelect('v_group', $this->Lang('group'), post('v_group', $USER->IUsers_AdminView->group));
$groupSel->add($this->Lang('all_groups'));
foreach($groups as $k=>$v){
	$groupSel->add($v['title'].' ['.$v['keyname'].']', $v['keyname']);
}

$fs->addInput('submit', 'v_submitBtn', '&nbsp;', $this->Lang('search'));
*/
$this->smarty->assign('form', $form->render());
$this->smarty->assign('view_query', (string) $sel);
$this->smarty->assign('tables', $tables);
$this->smarty->assign('pagination', $pagiLinks);
$this->smarty->assign('numResults', $numResults);
















































echo $this->ProcessTemplate('admin.view.tpl');
